package com.jpress.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jpress.facade.Facade;
import com.jpress.model.Blog;
import com.jpress.model.Comentario;
import com.jpress.model.CustomPage;
import com.jpress.model.Post;
import com.jpress.model.Usuario;

/**
 * Servlet implementation class PostCrudServlet
 */
@WebServlet({ 
	"/custompageexcluir.do", 
	"/custompageatualizar.do", 
	"/custompageeditar.do", 
	"/custompagecriar.do",
	"/custompageview.do"
})
public class CustomPageCrudServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CustomPageCrudServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Facade facade = new Facade();
		String custompageid = request.getParameter("custompageid");
		HttpSession session = request.getSession();
		Usuario logado = (Usuario) session.getAttribute("logado");
		
		if(logado != null){
			List<Blog> meusBlogs = facade.meusBlogs(logado.getId());
			List<Post> meusPosts = facade.meusPosts(logado.getId());
			List<Comentario> meusComentarios = facade.meusComentarios(logado.getId());
			request.setAttribute("titulopagina", "jPress - Principal");
			request.setAttribute("meusBlogs", meusBlogs);
			request.setAttribute("meusPosts", meusPosts);
			request.setAttribute("meusComentarios", meusComentarios);
		}
		
		CustomPage custompage = facade.getCustomPageById(Integer.parseInt(custompageid));
			
		//excluir customPage
		String origem = facade.paginaOrigem(request.getRequestURI());
		RequestDispatcher viewExcluir = request.getRequestDispatcher("custompagenova.jsp");
		if(origem.equals("custompageexcluir.do")){
			try {
				facade.excluirCustomPage(custompage);
				request.setAttribute("mensagemLog", "Custom Page excluida com sucesso!");
			} catch (Exception e) {
				request.setAttribute("mensagemErro", "Erro ao excluir a Custom Page" + custompage.getTitulo());
				e.printStackTrace();
			} finally{
				viewExcluir.forward(request, response);
			}
		}
		
		//editar customPage
		if(origem.equals("custompageeditar.do")){
			RequestDispatcher viewEdicao = request.getRequestDispatcher("custompageeditar.jsp");
			request.setAttribute("custompageEdicao", custompage);
			viewEdicao.forward(request, response);
		}
		
		//visualizar custompage
		if(origem.equals("custompageview.do")){
			RequestDispatcher viewGerencia = request.getRequestDispatcher("custompageview.jsp");
			request.setAttribute("customPageView", custompage);
			
			List<Post> postsBlog = facade.getPostsByBlogId(custompage.getBlog().getId());
			List<CustomPage> customPagesBlog = facade.getCustomPageByBlogId(custompage.getBlog().getId());
			request.setAttribute("postsBlog", postsBlog);
			request.setAttribute("customPagesBlog", customPagesBlog);
			viewGerencia.forward(request, response);
		}		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Facade facade = new Facade();
		HttpSession session = request.getSession();
		Usuario logado = (Usuario) session.getAttribute("logado");

		//pegar dados e jogar no main.jsp 
		List<Blog> meusBlogs = facade.meusBlogs(logado.getId());
		List<Post> meusPosts = facade.meusPosts(logado.getId());
		List<Comentario> meusComentarios = facade.meusComentarios(logado.getId());
		request.setAttribute("titulopagina", "jPress - Principal");
		request.setAttribute("meusBlogs", meusBlogs);
		request.setAttribute("meusPosts", meusPosts);
		request.setAttribute("meusComentarios", meusComentarios);
		
		//atualizar custom page
		String origem = facade.paginaOrigem(request.getRequestURI());
		if(origem.equals("custompageatualizar.do")){
			String titulo = request.getParameter("titulo");
			String conteudo = request.getParameter("conteudo");
			String customPageId = request.getParameter("custompageid");
			int idCustomPage = Integer.parseInt(customPageId);			
			CustomPage customPageAtual = facade.getCustomPageById(idCustomPage);
			customPageAtual.setTitulo(titulo);
			customPageAtual.setConteudo(conteudo);
			System.out.println("" + idCustomPage);
			RequestDispatcher viewAtualiza = request.getRequestDispatcher("custompageeditar.jsp");
			if(facade.atualizarCustomPage(customPageAtual)){
				request.setAttribute("mensagemLog", "Custom Page atualizada com sucesso!");
			}else{
				request.setAttribute("mensagemErro", "Erro ao atualizar a custom Page " + customPageAtual.getTitulo());
			}
			viewAtualiza.forward(request, response);
		}
		
		//criar Post
		if(origem.equals("custompagecriar.do")){
			int idBlog = Integer.parseInt((String)request.getParameter("blog"));
			String titulo = request.getParameter("titulo");
			String conteudo = request.getParameter("conteudo");
			CustomPage customPageNova = new CustomPage();
			try{
				customPageNova.setTitulo(titulo);
				customPageNova.setConteudo(conteudo);
				//System.out.println(customPageNovo);
				RequestDispatcher viewNovo = request.getRequestDispatcher("custompagenova.jsp");
				if(facade.cadastrarCustomPage(customPageNova, idBlog)){
					request.setAttribute("mensagemLog", "Custom Page cadastrada com sucesso!");
				}else{
					request.setAttribute("mensagemErro", "Erro ao cadastrar a novo Custom Page");
				}
				viewNovo.forward(request, response);
			}catch(Exception e){
				e.printStackTrace();
			}

		}
	}

}
